// pages/goods/product/groupDeatils.js
import {
  find,
  getOrderList
} from '../../../api/bargainBuy'
import {
  createQrcode,lockSysUser
} from '../../../api/member';
import {
  buyNowForBargainBuy
} from '../../../api/cart'
import css2canvas from "../../../utils/css2canvas"
import {
  add,
  exists,
  del
} from '../../../api/memberFavorites.js'
const util = require('../../../utils/util.js')
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderNow:[],
    nowId:'',
    shareType:false,
    canvasType: false,
    canvasHeight: 400,
    canvasH: 0,
    cardInfo: {
      TagText: "****", //标签
      Name: '****', //姓名
      rule: '',
      rule1: '',
      avater: "", //需要https图片路径
      qrCode: "", //需要https图片路径
      price: '**',
      logo: 'http://cdnx.rzico.com/images/canvasMyLogo.png',
      coupons: '',
      marketPrice: '',
      activityPrice: ''
    },
    history: 0,
    isShow: true,
    carvasQrCode: '',
    carvasLogo: '',
    carvasAvater: '',
    existsType: 0,
    qrcode: '',
    groupId: [],
    productId: '',
    content: '',
    heads: [

    ],
    product: {},
    hiddenNav: true,
    swiperIndex: 0,
    current: '1',
    navId: '0',
    swiperImg: [],
    swiperVideo: [],
    nav: ['商品', '规则', '详情'],
    statusBarHeight: '',
    canvasBottonTitle:'保存图片至相册'
  },
  backClick() {
    wx.navigateBack({
      delta: 1,
      fail: res => {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    })
  },
  createImageClick() {

    let data = encodeURIComponent(this.data.qrcode + '?bargainBuyId=' + this.data.product.id)
    console.log(data)
    this.data.cardInfo.qrCode = app.APP_BASE_API + '/zxing/createImage?data=' + data
    console.log(this.data.cardInfo.qrCode)
    this.setData({
      cardInfo: this.data.cardInfo
    })
  },
  createQrcodeClick() {
    if (app.globalData.token == null) {
      return;
    }
    createQrcode().then(res => {
      this.data.qrcode = res.content
      this.createImageClick()
    }).catch(error => {

    })
  },
  starShare(){
    this.data.shareType = !this.data.shareType
    this.setData({
      shareType:this.data.shareType
    })
  },
  cancelShare(){
    this.data.shareType = !this.data.shareType
    this.setData({
      shareType:this.data.shareType
    })
  },
  canvasClick() {
    var _this = this
    this.data.canvasType = true
    this.data.shareType=false
    this.data.cardInfo.avatar = this.data.product.thumbnail
    console.log(this.data.product.thumbnail)
    wx.getImageInfo({
      src: util.proxyImage(app.APP_BASE_API, util.thumbnail(_this.data.product.thumbnail, 600, 600)), //网络图片路径
      success: res => {
        _this.data.carvasAvater = res.path; //图片临时本地路径
        wx.getImageInfo({
          src: util.proxyImage(app.APP_BASE_API, util.thumbnail(_this.data.cardInfo.logo, 200, 200)), //网络图片路径
          success: res => {
            console.log(res.path, 's2')
            _this.data.carvasLogo = res.path; //图片临时本地路径
            wx.getImageInfo({
              src: _this.data.cardInfo.qrCode, //网络图片路径
              success: res => {
                console.log(res.path, 's2')
                this.data.carvasQrCode = res.path; //图片临时本地路径
                setTimeout(() => {
                  this.sharePosteCanvas()
                }, 1000)
                this.setData({
                  shareType:this.data.shareType,
                  canvasType: this.data.canvasType,
                  cardInfo: this.data.cardInfo
                })
              }
            })
          }
        })
      }
    })

  },

  cancleCanvasClick() {
    this.data.canvasType = false
    this.data.canvasBottonTitle = '保存图片至相册'
    this.setData({
      canvasType: this.data.canvasType,
      canvasBottonTitle:this.data.canvasBottonTitle
    })
  },
  saveShareImg: function () {
    var that = this;
    if(this.data.canvasBottonTitle == '去分享到朋友圈'){
      this.cancleCanvasClick()
      return
    }
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas-show',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              that.data.canvasBottonTitle = '去分享到朋友圈'
              that.setData({
                canvasBottonTitle:that.data.canvasBottonTitle
              })
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  nextClick() {
    
    if (this.data.nowId>0) {
      this.data.nowId-=1
      getOrderList({
        periodId: this.data.nowId,
  
      }).then(res => {
        if (res.type == 'success') {
  
          this.data.orderNow=res.data.orderItem
          this.setData({
            orderNow:this.data.orderNow
          })
        }
      })
    }
   
  },
  toMember() {
    wx.navigateTo({
      url: '/pages/goods/bargain/members?id=' + this.data.nowId,
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  indexClick() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  swiperChange(data) {
    var _this = this
    this.data.current = data.detail.current + 1
    this.setData({
      current: this.data.current
    })
  },

  // 画布海报
  sharePosteCanvas: function () {
    var _this = this
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var canvasShow = wx.createCanvasContext("canvas-show")
    let ctx = new css2canvas(canvasShow)
    var canvasForm = [{
      type: "roundRect",
      x: 0,
      y: 0,
      width: 550,
      height: 715,
      background: "#ffffff",
      borderWidth: 1,
      borderRadius: 0,
      clip: false
    },
    {
      type: "image",
      imgUrl: _this.data.carvasLogo,
      x: 20,
      y: 20,
      width: 60,
      height: 60,
      borderRadius: 30
    },
    {
      type: "text",
      x: 90,
      y: 20,
      color: "black",
      fontSize: 28,
      baseline: "top",
      content: _this.data.cardInfo.Name
    },

      {
        type: "text",
        x: 90,
        y: 56,
        color: "#999999",
        fontSize: 22,
        baseline: "top",
        content: "臻选好物，好友喊你来助力"
      },
      {
        type: "image",
        imgUrl: _this.data.carvasAvater,
        x: 20,
        y: 100,
        width: 398,
        height: 398
      },
      {
        type: "prefixText",
        x: 20,
        y: 545,
        color: "#FF3131",
        textAlign: "left",
        content: _this.data.cardInfo.price,
        tag: "￥",
        fontSize: 36,
        tagSize: 28
      },
      {
        type: "text",
        x: 20,
        y: 555,
        width: 270,
        content: _this.data.cardInfo.TagText,
        color: "#666666",
        fontSize: 24,
        textAlign: "left",
        overflow: "warp",
        maxLine: 1,
        lineHeight: 1
      },
      {
        type: "image",
        imgUrl: _this.data.carvasQrCode,
        x: 285,
        y: 515,
        width: 158,
        height: 158
      },
      {
        type: "tag",
        x: 20,
        y: 587,
        // background: '#faeef0',
        color: "#dd7f62",
        paddingTop: 5,
        paddingBottom: 5,
        // paddingLeft: 5,
        // paddingRight: 5,
        borderTopRadius: 10,
        fontSize: 24,
        content: _this.data.cardInfo.rule
      },
      {
        type: "tag",
        x: 20,
        y: 621,
        width: 300,
        height: 150,
        // background: '#faeef0',
        color: "#dd7f62",
        paddingTop: 5,
        paddingBottom: 5,
        // paddingLeft: 5,
        // paddingRight: 5,
        borderTopRightRadius: 10,
        fontSize: 24,
        content: _this.data.cardInfo.rule1
      },
    ]

    if (_this.data.cardInfo.marketPrice != '') {
      var marketPrice = {
        type: "prefixText",
        x: ctx.getWidth({
          text: "100",
          fontSize: 36,
          returnPx: false
        }) +
          74,
        y: 545,
        color: "#999999",
        textAlign: "left",
        content: _this.data.cardInfo.marketPrice,
        tag: "￥",
        fontSize: 28,
        tagSize: 20,
        isDel: true,
        delColor: "#999999"
      }
      canvasForm.push(marketPrice)
    }
    ctx
      .drawingView(canvasForm)
      .then(res => {
        console.log("绘制完成")
        wx.hideLoading();
      })
  },
  toBuy() {

    if (this.data.product.status == 2) {
      wx.showToast({
        title: "砍价已完成",
        icon: "none"
      })
      return
    } else {
      if (app.globalData.token == null) {
        wx.navigateTo({
          url: '/pages/login/index',
        })
      }
      buyNowForBargainBuy({
        uuid: app.globalData.uuid,
        bargainBuyId: this.data.product.id
      }).then(res => {
        if (res.type == 'success') {
          wx.navigateTo({
            url: '/pages/goods/submit/index?bargainBuyId=' + this.data.product.id,
            success: function (res) {},
            fail: function (res) {},
            complete: function (res) {},
          })
        }
      })
    }
  },
  loadProduct(data) {
    var _this = this
    this.data.groupId = []
    this.data.heads = []
    this.data.swiperIndex = 0
    this.data.content = []
    this.data.history = 0
    find(data).then(res => {
      if (res.data.bargainBuy.periodList.length>0) {
        this.data.nowId=res.data.bargainBuy.periodList[res.data.bargainBuy.periodList.length-1].id
      }
    if (res.data.bargainBuy.periodList.length>0) {
      getOrderList({
        periodId:res.data.bargainBuy.periodList[res.data.bargainBuy.periodList.length-1].id
      }).then(response=>{
          this.data.orderNow=response.data.orderItem
          this.setData({
            orderNow:this.data.orderNow
          })
      })
    }
      res.data.bargainBuy.meta = JSON.parse(res.data.bargainBuy.meta)
      this.data.product = res.data.bargainBuy
      this.data.product.point=(this.data.product.point/100).toFixed(2)
      this.data.product.mypoint=(this.data.product.point*0.3).toFixed(2)
      this.data.product.youpoint=(this.data.product.point*0.7).toFixed(2)
      this.data.cardInfo.TagText = res.data.bargainBuy.name
      this.data.cardInfo.price = res.data.bargainBuy.price
      if (res.data.bargainBuy.bargainNum<10&&(res.data.bargainBuy.point*0.003)<10) {
        this.data.cardInfo.rule='邀'+res.data.bargainBuy.bargainNum
        +'人砍价得1'+(res.data.bargainBuy.point*0.003).toFixed(1)+'红包'
        this.data.cardInfo.rule1='邀好友瓜分'+(res.data.bargainBuy.point*0.007).toFixed(1)+'红包  '
      }else if (res.data.bargainBuy.bargainNum<10&&(res.data.bargainBuy.point*0.003)>10) {
        this.data.cardInfo.rule='邀'+res.data.bargainBuy.bargainNum
        +'人砍价得'+(res.data.bargainBuy.point*0.003).toFixed(1)+'红包'
        this.data.cardInfo.rule1='邀请好友瓜分'+(res.data.bargainBuy.point*0.007).toFixed(1)+'红包 '
      }else if(res.data.bargainBuy.bargainNum>9&&(res.data.bargainBuy.point*0.003)<10){
        this.data.cardInfo.rule='邀'+res.data.bargainBuy.bargainNum
        +'人砍价得'+(res.data.bargainBuy.point*0.003).toFixed(1)+'红包'
        this.data.cardInfo.rule1='邀好友瓜分'+(res.data.bargainBuy.point*0.007).toFixed(1)+'红包    '
      }

      this.data.cardInfo.marketPrice = res.data.bargainBuy.marketPrice
      if (res.data.bargainBuy.periodNum > 0) {
        this.data.history = res.data.bargainBuy.periodNum - 1
      } else {
        this.data.history = 0
      }

      res.data.bargainBuy.periodList.forEach(item => {
        if (!item.avatar) {
          item.avatar = 'http://rzico.oss-cn-shenzhen.aliyuncs.com/img/hhahahah.jpg'
        }
      })
      if (res.data.bargainBuy.periodList.length > 9) {
         this.data.heads=[]
        res.data.bargainBuy.periodList[9].avatar = 'http://rzico.oss-cn-shenzhen.aliyuncs.com/img/more.png'
        for (let index = 0; index < 10; index++) {
          this.data.heads.push(res.data.bargainBuy.periodList[index])
        }
      } else {
        this.data.heads = res.data.bargainBuy.periodList

      }
      res.data.bargainBuy.itemList.forEach(item => {
        this.data.groupId.push(item.groupBuyId)
      })
      if (!util.isNull(res.data.bargainBuy.meta)) {
        if (!util.isNull(res.data.bargainBuy.meta.images)) {
          res.data.bargainBuy.meta.images.forEach(item => {
            item = util.thumbnail(item, 750, 750)
          })
          _this.data.swiperImg = res.data.bargainBuy.meta.images;
        }
        if (!util.isNull(res.data.bargainBuy.meta.video)) {
          _this.data.swiperVideo = res.data.bargainBuy.meta.video;
        }
      }
      if (!util.isNull(res.data.bargainBuy.content)) {
        const regex = new RegExp('<img', 'gi');
        _this.data.content = res.data.bargainBuy.content.replace(regex, `<img style="width: 100%;display:block"`);
      }
      if (_this.data.swiperVideo == '') {
        this.data.swiperIndex = _this.data.swiperImg.length
      } else {
        this.data.swiperIndex = _this.data.swiperImg.length + 1
      }
      this.setData({
        heads: this.data.heads,
        history: this.data.history,
        product: this.data.product,
        content: this.data.content,
        swiperIndex: this.data.swiperIndex,
        swiperImg: _this.data.swiperImg,
        swiperVideo: _this.data.swiperVideo
      })
    })
  },
  toScroll(e) {
    let index = e.currentTarget.dataset.index
    let mmp = ''
    switch (index) {
      case 0:
        mmp = 'anchor1'
        break;
      case 1:
        mmp = 'anchor2'
        break;
      case 2:
        mmp = 'anchor3'
        break;
      default:
        break
    }
    this.setData({
      toview: mmp
    })
  },
  // 监听滚动事件
  bindscroll(e) {
    let _this = this;
    let query = wx.createSelectorQuery()
    query.select('#anchor1').boundingClientRect()

    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      if (res[0].top > -200 && _this.data.hiddenNav == false) {
        _this.setData({
          hiddenNav: true
        })
      } else if (res[0].top < -190 && _this.data.hiddenNav == true) {
        _this.setData({
          hiddenNav: false
        })
      }
    })
    query.select('#anchor2').boundingClientRect()
    query.select('#anchor3').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      if (res[2].top < 66 && _this.data.navId != 1 && _this.data.navId != 2) {
        _this.setData({
          navId: 1
        })
      }
      if (res[2].top > 66 && _this.data.navId == 1) {
        _this.setData({
          navId: 0
        })
      }
      if (res[3].top < 66 && _this.data.navId != 2 && _this.data.navId == 1) {
        _this.setData({
          navId: 2
        })
      }
      if (res[3].top > 66 && _this.data.navId == 2) {
        _this.setData({
          navId: 1
        })
      }
    })
  },
  startLockSysUser() {
    lockSysUser({ mchId: app.globalData.mchId, xuid: app.globalData.xuid }).then(res => {
      console.log(res)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if (!util.isNull(options.xuid)) {
      app.globalData.xuid = options.xuid;
    }

    app.userInfoReadyCallback = res => {
      if (app.globalData.token != null) {
        this.startLockSysUser()
        util.forwarding(options, app.globalData.token)
      }
    }

    if (app.globalData.token != null) {
      this.startLockSysUser()
      util.forwarding(options, app.globalData.token)
    }


    this.loadProduct(options.id)

    this.data.productId = options.id
    setTimeout(() => {
      this.createQrcodeClick()
    }, 1000)

    this.data.canvasH = (wx.getSystemInfoSync().windowWidth / 750).toFixed(2)
    this.data.canvasHeight = 680 * this.data.canvasH
    this.setData({
      canvasH: this.data.canvasH,
      canvasHeight: this.data.canvasHeight,
      statusBarHeight: app.globalData.statusBarHeight,
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadProduct(this.data.productId)
    const {
      userInfo
    } = app.globalData
    if (userInfo) {
      //怎么判断是否已经头像授权
      if (userInfo.hasOwnProperty("avatar")) {
        // this.data.cardInfo.Name = app.globalData.userInfo.nickname
        this.data.cardInfo.logo = app.globalData.userInfo.avatar
        this.setData({
          cardInfo: this.data.cardInfo
        })
      }
      if (userInfo.hasOwnProperty("nickname")) {
        this.data.cardInfo.Name = app.globalData.userInfo.nickname

        this.setData({
          cardInfo: this.data.cardInfo
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onShareAppMessage: function () {
    console.log(this.data.product.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500')
    return {
      title: this.data.product.name,
      desc: '臻选好物，好友喊您来助力',
      imageUrl: this.data.product.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
      path: '/pages/goods/bargain/barginDetails?id=' + this.data.productId + '&xuid=' + app.globalData.userInfo.id
    }
  },
  onShareTimeline: function () {
    return {
      title: this.data.product.name,
      desc: '臻选好物，好友喊您来助力',
      path: '/pages/goods/bargain/barginDetails',
      query: 'id=' + this.data.productId + '&xuid=' + app.globalData.userInfo.id,
      imageUrl: this.data.product.thumbnail
    }
  },

})